﻿using System;
using System.Collections.Generic;

namespace TK
{
    public partial class CustomSerializer
    {
        void writeGenericTuple(CustomSerializerState state, object o)
        {
            var type = o.GetType();
            var gga = type.GetGenericArguments();

            var objID = state.writeHeader();
            state.writeUInt16((UInt16)gga.Length);
            
            var propInfos = getTypeProps(type, false);
            for (var i = 1; i <= gga.Length; i++) { // .GenericTypeArguments
                var propInfo = propInfos["Item" + i];
                var v = propInfo.GetValue(o);
                state.writeUInt16((UInt16) (v == null ? 0 : 1));
                writeValue(state, v, propInfo.Name);
            }
            state.updateHeader(objID);
        }

        object readGenericTuple(CustomSerializerState state, Type type)
        {
            var header = state.readHeader();
            var count = state.readUInt16();
            var list = new List<object>();
            var gga = type.GetGenericArguments();
            for (var i = 1; i <= count; i++) {
                var flag = state.readUInt16();
                bool success = false;
                list.Add(flag > 0 ? readValue(state, gga[i - 1], type, "Item" + i, out success) : null);
            }

            if (list.Count < gga.Length)
                list.AddRange(new object[gga.Length - list.Count]);

            return Activator.CreateInstance(type, list.ToArray(), null);
        }
    }
}